//微信支付
const requestPayment = (query) => {
  console.log('【微信支付】', query);
  return new Promise((resolve, reject) => {
    // "provider": "wxpay",
    uni.requestPayment({
      timeStamp: query.timeStamp,
      paySign: query.paySign,
      nonceStr: query.nonceStr,
      package: query.package,
      signType: query.signType,
      success(res) {
        resolve(res);
      },
      fail(err) {
        reject(err);
      },
    });
  });
};
/**
 * 时间格式化
 * @param { String } time 当前时间
 * @param { String } type 0-精确到日 1-精确到秒
 */
const formatting = (val, format = 'YYYY-MM-DD') => {
  if (!val) return '';
  const date = new Date(val);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');

  let formatted = format;
  formatted = formatted.replace('YYYY', year);
  formatted = formatted.replace('MM', month);
  formatted = formatted.replace('DD', day);
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  formatted = formatted.replace('HH', hours);
  formatted = formatted.replace('mm', minutes);
  formatted = formatted.replace('ss', seconds);
  return formatted;
};
/**
 * 文字轻提示
 * @param { String } 提示文字
 * @param { Number } icon 提示icon
 * @param { Number } duration 提示时间
 */
const alert = (str, icon = 0, duration = 1500) => {
  uni.showToast({
    title: str + '',
    icon: ['none', 'success', 'loading'][icon],
    duration: duration,
  });
};
/**
 * loading加载
 * @param { String } str 加载文案
 * @param {*} mask
 */
const loading = (str = ' ', mask = true) => {
  uni.showLoading({
    title: str,
    mask: mask,
  });
};
/**
 * 关闭loading提示框
 */
const loading_h = () => {
  uni.hideLoading();
};

/**
 * 可返回跳转
 * @param { String } url 页面地址
 */
const jump_nav = (url) => {
  if (!url.startsWith('/')) {
    url = '/' + url;
  }
  uni.navigateTo({
    url: url,
    fail: (err) => {
      uni.switchTab({
        url: url,
      });
    },
  });
};
/**
 * 不可返回跳转
 * @param { String } url 页面地址
 */
const jump_red = (url) => {
  uni.redirectTo({
    url: url,
  });
};
/**
 * 清除页面栈跳转
 * @param { String } url 页面地址
 */
const jump_rel = (url) => {
  uni.reLaunch({
    url: url,
  });
};
/**
 * 跳转tabBar页
 * @param { String } url 页面地址
 */
const jump_swi = (url) => {
  uni.switchTab({
    url: url,
  });
};
/**
 * 返回上一页面
 * @param { Number } delta 返回层级
 */
const jump_back = (delta) => {
  var pages = getCurrentPages();
  var prevPage = pages[pages.length - 2];
  if (prevPage == undefined) {
    uni.reLaunch({
      url: '/pages/index/index',
    });
  } else {
    uni.navigateBack();
  }
};
/**
 * 跳转视频号
 * @param { String } spId
 * @param { String } feedId
 */
const openChannelsActivity = (spId, feedId) => {
  uni.openChannelsActivity({
    finderUserName: spId,
    feedId: feedId,
    success: (res) => {
      console.log('打开成功', res);
    },
    fail: (err) => {
      console.log(err);
    },
  });
};
/**
 * 跳转小程序
 * @param { String } url 跳转小程序的落地地址
 * @param { String } appid
 */
const toApplet = (url, appid) => {
  uni.navigateToMiniProgram({
    appId: appid,
    path: url,
    success: (res) => {
      console.log('打开成功', res);
    },
    fail: (err) => {
      console.log(err);
    },
  });
};
/**
 * 操作本地缓存
 * @param { String } key 缓存键值
 * @param { String } value 缓存数据
 */
const storage = (key, value) => {
  if (value != null) {
    uni.setStorageSync(key, value);
  } else {
    if (key == null) {
      return uni.getStorageInfoSync();
    } else {
      if (key != '#') {
        if (key[0] == '#') {
          uni.removeStorageSync(key.slice(1));
        } else {
          return uni.getStorageSync(key);
        }
      } else if (key == '#') {
        uni.clearStorageSync();
      }
    }
  }
};
/**
 * 导入外部字体
 * @param { String } name 字体
 */
const getFonts = (name) => {
  let url = config.ASSETSURL; //自己服务器的域名(或IP)
  let source = 'url(' + url + name + ')';
  console.log(source);
  uni.loadFontFace({
    family: name.substring(0, name.length - 4), //名称去掉后缀
    source: source,
    global: true,
    success(res) {
      console.log('load ' + name.substring(0, name.length - 4) + ' success');
      //   console.log(res)
    },
    fail(res) {
      console.log('load ' + name.substring(0, name.length - 4) + ' failed');
      console.log(res); //出错则打印信息
    },
  });
};
// 长按保存功能--授权部分
const saveImage = (url) => {
  console.log('【保存保存图片】', url);
  let _this = this;
  uni.showActionSheet({
    itemList: ['保存到相册'],
    success(res) {
      uni.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            uni.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                // 同意授权
                _this.saveImgInner(url);
              },
              fail: (res) => {
                console.log(res);
                uni.showModal({
                  title: '保存失败',
                  content: '请开启访问手机相册权限',
                  success(res) {
                    uni.openSetting();
                  },
                });
              },
            });
          } else {
            // 已经授权了
            _this.saveImgInner(url);
          }
        },
        fail: (res) => {
          console.log(res);
        },
      });
    },
    fail(res) {
      console.log(res.errMsg);
    },
  });
};

// 长按保存功能--保存部分
const saveImgInner = (url) => {
  uni.getImageInfo({
    src: url,
    success: (res) => {
      let path = res.path;
      uni.saveImageToPhotosAlbum({
        filePath: path,
        success: (res) => {
          console.log(res);
          uni.showToast({
            title: '已保存到相册',
          });
        },
        fail: (res) => {
          console.log(res);
        },
      });
    },
    fail: (res) => {
      console.log(res);
    },
  });
};
const tool = {
  requestPayment,
  formatting,
  alert,
  loading,
  loading_h,
  jump_nav,
  jump_red,
  jump_rel,
  jump_swi,
  jump_back,
  storage,
  getFonts,
  saveImage,
};
export default {
  tool,
};
